package com.zking.dao;

import com.zking.dao.CategoryDao;
import com.zking.entity.Category;
import com.zking.util.DBUtil;
import java.util.ArrayList;
import java.util.List;

public class CategoryDao{
    public static List<Category> getAllCategory() {
        List<Category> list = new ArrayList<Category>();
        List<Category> bigList = getBigCategory();
        for (Category big : bigList) {
            list.add(big);//先添加大类
            Integer pId = big.getEpc_id();//这个大类的id
            List<Category> smallList = getSmallCategoryByPid(pId);//该大类下的小类
            list.addAll(smallList);//添加大类下对应的小类
        }
        return list;
    }

    public static List<Category> getBigCategory() {
        String sql = "select * from easybuy_product_category where epc_id=epc_parent_id";
        return DBUtil.query(sql, Category.class);
    }

    public static Integer getBigCategoryIdByChildId(int epc_id) {
        String sql = "select epc_parent_id from easybuy_product_category where epc_id=?";
        return DBUtil.query(sql, Category.class, epc_id).get(0).getEpc_parent_id();
    }

    public static List<Category> getSmallCategoryByPid(int pId) {
        String sql = "select * from easybuy_product_category where epc_parent_id=? and  epc_id!=epc_parent_id";
        return DBUtil.query(sql, Category.class,pId);
    }

    public static List<Category> getSmallCategory() {
        String sql = "select * from easybuy_product_category where epc_id!=epc_parent_id";
        return DBUtil.query(sql, Category.class);
    }

    public static boolean addCategory(Category category) {
        String sql = "insert into easybuy_product_category values(?,?,?)";
        return DBUtil.update(sql,category.getEpc_id() ,category.getEpc_name(),category.getEpc_parent_id());
    }

    public static Category getCategoryById(int epc_id) {
        String sql = "select * from easybuy_product_category where epc_id=?";
        List<Category> list = DBUtil.query(sql, Category.class, epc_id);
        if(list.size()==1){
            return  list.get(0);
        }
        return null;
    }

    public static boolean updateCategory(Category category) {
        String sql = "update easybuy_product_category set epc_name=?,epc_parent_id=? where epc_id=?";

        return DBUtil.update(sql,category.getEpc_name(),category.getEpc_parent_id(),category.getEpc_id());
    }

    public static int getCategoryCount() {
        String sql = "select * from easybuy_product_category";
        List<Category> list = DBUtil.query(sql, Category.class);
        return list.size();
    }

}
